import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:bruno/bruno.dart';

// import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';

// import 'package:image_pickers/image_pickers.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:get/route_manager.dart';

import '../../../router/app_pages.dart';
import '../../../services/address.dart';
import '../../../services/dio_manager.dart';
import '../calendar_alarm_view.dart';
import '../calendar_room_view.dart';
import 'published_calendar_model.dart';

class PublishedCalendarController extends GetxController {
  int calendar_id = 0;
  double intensity = 0.34;

  List<String> userIdName = ['请选择组织人'];
  List<int>? userId;

  List<String> userIdsName = ['请选择参与者'];
  List<int>? userIds;

  List<String> shareUserIdsName = ['请选择共享人'];
  List<int>? shareUserIds;

  List<String>alarmName = ['提醒类型'];
  List<int>alarmNameId = [];


  bool isAllDaily = false; /// 是否全天

  // var activenames = [];
  // var activearraids = [];
  // var activestrings = "请选择";


  var roomName = '请选择会议室';
  var roomId = '';

  var privacyName = '选择公开程度';
  var privacyId = '';

  TextEditingController editingController = TextEditingController();
  TextEditingController editingController1 = TextEditingController();
  TextEditingController durationTimeTF = TextEditingController();
  TextEditingController locationTF = TextEditingController();

  String start_time = "请选择开始时间";
  String ended_time = "请选择结束时间";

  ///删除任务
  requestDataDelete() async {
    Map<String, dynamic> hashmap = {};
    hashmap['calendar_id'] = calendar_id;
    var formData = FormData.fromMap(hashmap);
    var json = await DioManager().kkRequest(Address.calendarUnlink,
        bodyParams: formData, isShowLoad: true);
    if (json['errmsg'] == 'ok') {
      Get.back(result: 'refresh');
    }
    BotToast.showText(text: json['message']);
  }

  /// 发送请求
  requestDataWithPublish() async {
    var params = {
      'name':editingController.text, ///日常名称
      'user_ids':userIds?.join(','), ///参与人
      'share_user_ids':shareUserIds?.join(','), ///共享人
      'user_id':userId?[0], ///组织人
      'start_time':'${start_time}', ///全天的不要时分秒，不是的需要带上时分秒
      'end_time':'${ended_time}', ///全天的不要时分秒，不是的需要带上时分秒
      'allday':isAllDaily==true?'1':'0', ///是否全天
      'duration':'${durationTimeTF.text}', ///持续时间（小时）
      'description':editingController1.text, ///描述
      'room_id':roomId, ///会议室
      'location':'${locationTF.text}', ///
      'privacy':'${privacyId}', ///
      // 'recurrency':'', ///是否循环日程
      // 'rrule_type':'', ///rrule_type
      'calendar_id':'0', ///日程ID：0-新增
      'alarm_ids':alarmNameId.join(','),
      // 'edit_type':'self', ///如果是循环日程，编辑类型 self-本身事件，after-本次及以后，all-所有事件
    };
    var json = await DioManager().kkRequest(Address.calendarCreate,
        bodyParams: params, isShowLoad: true);
    if (json['errmsg'] == 'ok') {
      Get.back(result: 'refresh');
    }
    BotToast.showText(text: json['message']);
  }

  /// 刷新滑动组件
  refreshSlider(double value) {
    intensity = value;
    update();
  }
  /// 点击选择组织人
  taoClickUser()async{
    var params = {
      'isMultiple':false,
      'personnelIdArr':userId,
      // 'personnelNameArr':userIdName
    };

    var data = await Get.toNamed(AppRoutes.personnel,arguments: params);
    print('data======${data}');
    if(data != null){
      print(data);
      userIdName.remove('请选择组织人');
      userIdName = data['personnelNameArr'];
      userId = data['personnelIdArr'];
      update();
    }
  }

  /// 点击选择参与者
  tapClickUserIds()async{

    var params = {
      'isMultiple':true,
      'personnelIdArr':userIds,
      'personnelNameArr':userIdsName,
    };
    var data = await Get.toNamed(AppRoutes.personnel,arguments: params);

    if(data!=null){
      print(data);
      userIdsName.remove('请选择参与者');
      userIdsName = data['personnelNameArr'];
      userIds = data['personnelIdArr'];
      // controller.refresh();
      update();
    }
  }
  /// 共享人员
  tapClickShareUser()async{
    var params = {
      'isMultiple':true,
      'personnelIdArr':shareUserIds,
      'personnelNameArr':shareUserIdsName,
    };
    var data = await Get.toNamed(AppRoutes.personnel,arguments: params);
    if(data!=null){
      print(data);
      shareUserIdsName.remove('请选择共享人');

      shareUserIdsName = data['personnelNameArr'];
      shareUserIds = data['personnelIdArr'];
      update();
    }
  }

  /// 点击选择会议室
  tapClickRoom()async{
    var data = await Get.to(CalendarRoomView());
    if(data!= null){
      roomName = data['name'];
      roomId = data['id'];
    }
    update();
  }
  /// 提醒类型
  tapClickAlarmType()async{
    var data = await Get.to(CalendarAlamView());
    if(data!= null){
      alarmName[0] = data['name'];
      alarmNameId = [data['id']];
    }
    update();
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    calendar_id = Get.arguments;
    if (calendar_id > 0) {
      // requestCalendarDetails();
    }
  }

  /// 点击附件icon
  tapClickAccessory(List accessary) {
    List<BrnCommonActionSheetItem> actions = [];
    accessary.forEach((element) {
      actions.add(BrnCommonActionSheetItem(
        element,
        actionStyle: BrnCommonActionSheetItemStyle.normal,
      ));
    });
    showModalBottomSheet(
        context: Get.overlayContext!,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return BrnCommonActionSheet(
            title: "",
            actions: actions,
            clickCallBack: (
              int index,
              BrnCommonActionSheetItem actionEle,
            ) async {
              print("tapClickAccessory===>>>$index");
              privacyName = accessary[index];
              privacyId = accessary[index]=='公开的'?'public'
                  :accessary[index]=='私人可见'?'private':'confidential';
              update();
            },
          );
        });
  }
}
